<template>
  <div>
    <el-row>
      <el-col :span="4">
        <!-- 复用设备树结构 -->
        <div class="tree">
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="filterText"
          ></el-input>
          <el-tree
            class="filter-tree"
            :data="empData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div v-if="currentDevice.id">
          <el-alert
            title="实时数据每5秒自动刷新"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 20px"
          />
          <el-table :data="realTimeData" v-loading="loading">
            <el-table-column
              prop="createTime"
              label="更新时间"
              width="180"
              align="center"
            >
              <template slot-scope="{ row }">
                {{ formatTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="tsp"
              label="TSP"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="pm10"
              label="PM10"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="pm25"
              label="PM2.5"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="temperature"
              label="温度(℃)"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="humidity"
              label="湿度(%)"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="windSpeed"
              label="风速(m/s)"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="windDirection"
              label="风向"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
        <div
          v-else
          style="text-align: center; color: #909399; line-height: 100px"
        >
          请选择设备查看实时数据
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { get } from "@/utils/request";
import dayjs from "dayjs";

export default {
  data() {
    return {
      filterText: "",
      empData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      currentDevice: {
        id: null,
        engineer_id: null,
      },
      realTimeData: [],
      loading: false,
      refreshTimer: null,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 格式化时间显示
    formatTime(time) {
      return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
    },

    // 节点点击处理
    handleNodeClick(nodeData) {
      if (!nodeData.children) {
        this.currentDevice = {
          id: nodeData.id,
          engineer_id: nodeData.engineer_id,
        };
        this.startAutoRefresh();
      }
    },

    // 开始自动刷新
    startAutoRefresh() {
      this.fetchRealTimeData();
      this.refreshTimer = setInterval(() => {
        this.fetchRealTimeData();
      }, 5000);
    },

    // 获取实时数据
    // 修改后的fetchRealTimeData方法
    async fetchRealTimeData() {
      try {
        if (!this.currentDevice.engineer_id || !this.currentDevice.id) return;

        this.loading = true;
        const params = {
          engineer_id: Number(this.currentDevice.engineer_id),
          device_id: Number(this.currentDevice.id),
          page: 1,
          pageSize: 1, // 只需要最新一条数据
        };

        const res = await get("/dashboard/pageQueryTodayData", params);

        // 调整数据结构映射
        if (res.data?.list?.length > 0) {
          this.realTimeData = [res.data.list[0]]; // 注意list层级
        }
      } catch (error) {
        console.error("获取实时数据失败:", error);
      } finally {
        this.loading = false;
      }
    },

    // 复用过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 获取设备树数据
    async getEmpData() {
      const res = await get("/dashboard/findEngineerDeviceTree");
      this.empData = res.data;
    },
  },
  beforeDestroy() {
    // 清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
  created() {
    this.getEmpData();
  },
};
</script>

<style lang="scss" scoped>
.tree {
  height: calc(100vh - 60px);
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
  margin-right: 10px;
  overflow: auto;
}

::v-deep .el-table__row {
  transition: background-color 0.3s ease;

  &:hover {
    background-color: #f5f7fa;
  }
}
</style>